package com.deshan.websys.api.controller;

import java.util.List;
import java.util.Objects;

import org.springframework.web.bind.annotation.DeleteMapping;
import org.springframework.web.bind.annotation.GetMapping;
import org.springframework.web.bind.annotation.PathVariable;
import org.springframework.web.bind.annotation.PostMapping;
import org.springframework.web.bind.annotation.RequestBody;
import org.springframework.web.bind.annotation.RequestMapping;
import org.springframework.web.bind.annotation.RequestParam;
import org.springframework.web.bind.annotation.RestController;

import com.baomidou.mybatisplus.core.conditions.query.LambdaQueryWrapper;
import com.baomidou.mybatisplus.core.toolkit.Wrappers;
import com.deshan.websys.api.utils.CommonResult;
import com.deshan.websys.code.model.Customers;
import com.deshan.websys.code.service.CustomersService;

import cn.hutool.core.util.ArrayUtil;
import cn.hutool.core.util.StrUtil;
import io.swagger.annotations.Api;
import io.swagger.annotations.ApiOperation;
import io.swagger.annotations.ApiParam;
import lombok.AllArgsConstructor;

@Api(tags = "用户和客服后台管理")
@RestController
@RequestMapping("/manage/user")
@AllArgsConstructor
public class UserController {

	private final CustomersService customersService;

	@ApiOperation("创建和修改")
	@PostMapping("/save")
	public CommonResult saveCustomers(@RequestBody Customers customers) {
		return customersService.saveOrUpdate(customers) ? CommonResult.success() : CommonResult.failed("保存失败");
	}

	@ApiOperation("删除")
	@DeleteMapping("/delete/{id}")
	public CommonResult deleteCustomers(@PathVariable("id") String id) {
		if (StrUtil.isBlank(id)) {
			return CommonResult.success();
		}
		return customersService.removeById(id) ? CommonResult.success() : CommonResult.failed("删除失败");
	}

	@ApiOperation("批量删除")
	@DeleteMapping("/delete/{ids}")
	public CommonResult batchDeleteCustomers(@PathVariable("ids") String[] ids) {
		if (ArrayUtil.isNotEmpty(ids)) {
			for (String id : ids) {
				deleteCustomers(id);
			}
		}
		return CommonResult.success();
	}

	@ApiOperation("查询当前法人下的所有客户或者客服")
	@GetMapping("/list/{legalCode}/{roleType}")
	public CommonResult<List<Customers>> listCustomers(@PathVariable("legalCode") String legalCode,
			@ApiParam(name="角色类型", value = "2:客服, 3:客户") @PathVariable("roleType") Integer roleType) {
		LambdaQueryWrapper<Customers> wrapper = Wrappers.lambdaQuery(Customers.class).eq(Customers::getMainCor,
				legalCode);
		if (Objects.nonNull(roleType)) {
			wrapper.eq(Customers::getRoleType, roleType);
		}
		return CommonResult.success(customersService.list(wrapper));
	}

	@ApiOperation("根据ID查询客户或者客服")
	@GetMapping("/getone")
	public CommonResult<Customers> getCustomers(@RequestParam("id") String id) {
		return CommonResult.success(customersService.getById(id));
	}
}
